<?php
class User extends Controller {

	/**
	 * Constructor
	 */
	function User(){
		parent::Controller();
		$this->load->model('User_model');
	}
	
	/**
	 * Register a new user into the database
	 */
	function register(){
		if ($this->auth->has_rights_to("add","user"))
		{
			$pwd1 = $this->input->post('pwd1');
			$pwd2 = $this->input->post('pwd2');
			
			$infos = array (
				'nickname' => $this->input->post('nickname'),
				'firstname' => $this->input->post('firstname'),
				'lastname' => $this->input->post('lastname'),
				'email' => $this->input->post('email')
			);
			
			if($pwd1===$pwd2){
				$result = $this->User_model->new_user($infos, $pwd1);
				if (!is_array($result)) {
					$this->load->library('email');
					$this->email->from('noreply@cero-devel.info', 'Cero Repository');
					$this->email->to($this->User_model->data['email']);
					$this->email->subject('Welcome to Cero Repository');
					$this->email->message('You just registered to Cero Repository. ' .
							'Please keep these information safe :' .
							'\n\tLogin : '.$this->User_model->data['email'].
							'\n\tPassword : '.$this->input->post('pwd1'));
					//$this->email->send();
					echo 'You successfully registered. An e-mail was sent to your adress ' .
							'('.$this->User_model->data['email'].')';
				}
				else {
					$param = array();
					$param['values'] = array();
					foreach($infos as $key => $value){
						if(isset($result[$key])){
							$param['values'][$key.'_val'] = '';
						}else{
							$param['values'][$key.'_val'] = $value;
						}
					}
					
					foreach($infos as $key => $value){
						$param['errors'][$key.'_err'] = '';
					}
					foreach($result as $key => $value){
						$param['errors'][$key.'_err'] = $value;
					}
					$param['errors']['pwd1_err'] = $param['errors']['pwd2_err'] = 
					$param['values']['pwd1_val'] = $param['values']['pwd2_val'] = '';
				}
			}else{
				$param['values'] = array('nickname_val' => '', 'firstname_val' => '','lastname_val' => '','email_val' => '','pwd1_val' => '','pwd2_val' => '');
				$param['errors'] = array('nickname_err' => '', 'firstname_err' => '','lastname_err' => '','email_err' => '','pwd1_err' => '','pwd2_err' => '');
				$param['errors']['pwd2_err'] = 'Passwords are not identical';
			}

			if (isset($param)) {
				$this->load->view('user/add', $param);
			}
		}
		else
		{
     		$this->load->view('forbidden');
		}
	}
	
	/**
	 * Display the authentification form into the login div
	 */
	function showlogin(){
		$this->load->view('auth/login');
	}
	
	/**
	 * Log in a user
	 */
	function login() {
		$data = array(
			'login' => $this->input->post('login'),
			'password' => $this->input->post('password'),
			'autologin' => $this->input->post('autologin'));
		if (!$this->_login($data)){
			$this->load->view('auth/login');
			echo 'Authentification error';
		} else {
			$this->load->view('auth/logged');
		}
	}
	
	private function _login($data, $hashed = false) {
		$login_result = $this->auth->login($data['login'], $data['password'], $hashed);
		$this->auth->set_autologin($data['autologin']);
		return ($login_result);
	}
	
	/**
	 * Log out a user
	 */
	function logout() {
		$this->auth->logout();
		$this->load->view('auth/logout');
	}
	
	/**
	 * Display the user's homepage
	 */
	function homepage($page=0){
		$data = $this->auth->get_infos();
		$this->load->model('Package_model');
		$this->load->model('Article_model');
		
		$data['pkgtitle'] = "Your packages";
		$data['articletitle'] = "Your articles";
		
		$data['pkglist'] = $this->Package_model->get_packages(null, null, 
		array('resp_usr' => $data['user_id'], 'status' => 'active'));
     	if (!is_array($data['pkglist']))
     		$this->load->view('system_error');
     	else
			$this->load->view('user/homepage', $data);
	}
	
	/**
	 * Display the add user form
	 */
	function add(){
		if ($this->auth->has_rights_to("add","user"))
		{
			$param['values'] = array('nickname_val' => '', 'firstname_val' => '','lastname_val' => '','email_val' => '','pwd1_val' => '','pwd2_val' => '');
			$param['errors'] = array('nickname_err' => '', 'firstname_err' => '','lastname_err' => '','email_err' => '','pwd1_err' => '','pwd2_err' => '');
			$this->load->view('user/add', $param);
		}
		else
		{
     		$this->load->view('forbidden');
		}
	}
	
	/**
	 * Display the profile of the user $id
	 */
	function profile($id){
		if (is_numeric($id) && $this->auth->has_rights_to("lookat", "user", $id))
		{
			$this->User_model->load_user_from_id($id);
			$data = $this->User_model->data;
	     	if (!is_array($data))
	     		$this->load->view('system_error');
	     	else
				$this->load->view('user/profile', $data);
		}
		else
		{
     		$this->load->view('forbidden');
		}
	}
	
	/**
	 * Display the userlist with pagination
	 */
	function userlist($page=0){
		if ($this->auth->has_rights_to("list","user"))
		{
			$this->load->library('paginationajax');
			
			$config['base_url'] = site_url("user/userlist");
			$config['total_rows'] = $this->User_model->get_user_count();
			$config['per_page'] = '5';
			$config['js_function'] = 'update_content';

			$data['usertitle'] = "All users";
			$data['userlist']=$this->User_model->get_users($page, $config['per_page']);
	     	if (!is_array($data['userlist']))
	     		$this->load->view('system_error');
	     	else {
				$this->paginationajax->initialize($config);
				$data['pagination']=$this->paginationajax->create_links();
				$this->load->view('user/list',$data);
	     	}
		}
		else
		{
     		$this->load->view('forbidden');
		}
	}
	
	/**
	 * Display the user search form
	 */
	function search(){
		if ($this->auth->has_rights_to("list","user"))
		{
			$this->load->view('user/search');
		}
		else
		{
     		$this->load->view('forbidden');
		}
	}
	
	/**
	 * Display the results of the search form with pagination with $searchkey matching $searchvalue.
	 */
	function userresults($searchkey, $searchvalue, $page=0 ){
		if ($this->auth->has_rights_to("list","user"))
		{
			$this->load->model('User_model');
			$this->load->library('paginationajax');
			
			$config['base_url'] = site_url('user/userresults/'.$searchkey.'/'.$searchvalue.'/');
			$config['per_page'] = '5';
			$config['js_function'] = 'update_search';
			$config['uri_segment'] = '5';
			$match = array ($searchkey => $searchvalue);
			$config['total_rows'] = $this->User_model->get_user_count($match);
			
			$data['usertitle'] = 'Users matching "'.$searchvalue.'"';
			
			$data['userlist']=$this->User_model->get_users($page, $config['per_page'], $match);
	     	if (!is_array($data['userlist']))
	     		$this->load->view('system_error');
	     	else {
				$this->paginationajax->initialize($config);
				$data['pagination']=$this->paginationajax->create_links();
				$this->load->view('user/list',$data);
	     	}
		}
		else
		{
     		$this->load->view('forbidden');
		}
	}
	
	/**
	 * Display the edit user view in order to edit the user $id
	 */
	function edit($id){
		if (is_numeric($id) && $this->auth->has_rights_to("edit","user", $id))
		{
			$this->User_model->load_user_from_id($id);
			$data = $this->User_model->data;
	     	if (!is_array($data))
	     		$this->load->view('system_error');
	     	else
				$this->load->view('user/edit', $data);
		}
		else
		{
     		$this->load->view('forbidden');
		}
	}
	
	/**
	 * Save the new information of the user into the database
	 */
	function edit_user($user_id){
		if (is_numeric($user_id) && $this->auth->has_rights_to("edit", "user", $user_id))
		{
			$infos = array (
				'nickname' => $this->input->post('nickname'),
				'firstname' => $this->input->post('firstname'),
				'lastname' => $this->input->post('lastname'),
				'email' => $this->input->post('email')
			);
			
			$pwd1 = $this->input->post('pwd1');
			$pwd2 = $this->input->post('pwd2');
			
			$password = null;
			if ($pwd1 != '' && $pwd1===$pwd2)
				$password = $pwd1;
			
			$usrrights = $this->input->post('rights');
			$levels = array(1 => 'usr', 2 => 'mod', 3 => 'smod', 4 => 'admin');
			if ($this->auth->has_rights_to("add", $levels[$usrrights]))
				$infos['rights'] = $usrrights;

			if (!$this->User_model->save_user($user_id, $infos, $password))
	     		$this->load->view('system_error');
	     	else
	     		$this->load->view('editOK');
		}
		else
		{
     		$this->load->view('forbidden');
		}
	}
}
?>
